package net.mayee.common;

import jodd.log.Logger;
import jodd.log.LoggerFactory;
import jodd.props.Props;
import net.mayee.alice.common.Definiens;
import net.mayee.common.utils.ValidateCode;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;

public class AliceHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliceHelper.class);
    private String applicationConfigFileClassPath;
    private Props props;

    private AliceHelper() {
        initAliceHelper();
    }

    private static final AliceHelper aliceHelper = new AliceHelper();

    public static AliceHelper getInstance() {
        return aliceHelper;
    }

    private void initAliceHelper() {
    }

    public String getApplicationConfigFileClassPath() {
        return applicationConfigFileClassPath;
    }

    public void setApplicationConfigFileClassPath(
            String applicationConfigFileClassPath) {
        this.applicationConfigFileClassPath = applicationConfigFileClassPath;
    }

    public void setJoddProps(Props props) {
        this.props = props;
    }

    public Props getJoddProps() {
        return this.props != null ? this.props : initJoddProps();
    }

    private Props initJoddProps() {
        Props p = new Props();
        ResourceLoader loader = new DefaultResourceLoader();
        Resource resource_app = loader.getResource(this.applicationConfigFileClassPath);
        if (resource_app.exists()) {
            try {
                p.load(resource_app.getInputStream(), Definiens.CHARSET_UTF8);
            } catch (IOException e) {
                LOGGER.error("**** AliceHelper -> initJoddProps fail! ****", e);
            }
        }
        return p;
    }

    public boolean checkValidateImg(String vi_code, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session.getAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG) != null) {
            String session_vi_code = (String) request.getSession().getAttribute(
                    Definiens.SESSIONKEY_LOGIN_VALIDATEIMG);
            return session_vi_code.equals(vi_code.toUpperCase());
        }
        return false;
    }

    public void removeValidateImg(HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        if (session.getAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG) != null) {
            File f = new File(
                    session.getServletContext().getRealPath("/")
                            + (String) session.getAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG_PATH));
            if (f.exists()) {
                f.delete();
            }
            session.removeAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG);
            session.removeAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG_PATH);
        }
    }

    public String buildOrResetValidateImg(HttpServletRequest request)
            throws IOException {
        HttpSession session = request.getSession();

        /* def line count */
        int def_validateimg_line_count = Definiens.DEF_VALIDATEIMG_LINE_COUNT;
        try{
            def_validateimg_line_count = Integer.parseInt(props.getValue("validateimg.line.count"));
        }catch (Exception e){
            LOGGER.error(
                    getApplicationConfigErrorMessage("validateimg.line.count", def_validateimg_line_count), e);
        }

        ValidateCode vCode = new ValidateCode(130, 32, 5, def_validateimg_line_count);
        String rPath = Definiens.DEF_VALIDATEIMG_SAVEPATH_LOGIN
                + Calendar.getInstance().getTimeInMillis() + ".png";
        vCode.write(session.getServletContext().getRealPath("/") + rPath);

        session.setAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG,
                vCode.getCode());
        session.setAttribute(Definiens.SESSIONKEY_LOGIN_VALIDATEIMG_PATH,
                rPath);
        return rPath;
    }

    public String getApplicationConfigErrorMessage(String configKey, Object defVal) {
        StringBuffer sb = new StringBuffer("非法的参数配置，[application.properties - ");
        sb.append(configKey).append("]，已重置为默认值[").append(defVal).append("]");
        return sb.toString();
    }

}
